/*
CheckoutCheck is Copyright 2010 Polyclef Software LLC.

This file is part of CheckoutCheck.

    CheckoutCheck is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    CheckoutCheck is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with CheckoutCheck.  If not, see <http://www.gnu.org/licenses/>.
*/

package com.checkoutcheck;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.math.BigDecimal;
import java.math.MathContext;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.apache.commons.codec.binary.Base64;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.checkoutcheck.R;
import com.flurry.android.FlurryAgent;
import com.google.ads.AdSenseSpec;
import com.google.ads.GoogleAdView;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.util.Linkify;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class CheckoutCheck extends Activity implements Runnable {

	private static final int INFORMATION_DIALOG = 0;
	private static final int EDIT_MERCHANT_INFORMATION = 1;
	private Button btnConnect;
	private Button backButton;
	ProgressDialog myProgressDialog;
	private String startMonth,startDay,startYear,endMonth,endDay,endYear;
	private String endTime;
	private int currentMonth, currentDay, currentYear, currentHour, currentMinute;
	private Spinner startMonthSpinner;
	private Spinner startDaySpinner;
	private Spinner startYearSpinner;
	private Spinner endMonthSpinner;
	private Spinner endDaySpinner;
	private Spinner endYearSpinner;
	private Spinner orderStateSpinner;
	private Spinner transactionFeeSpinner;
	private ArrayAdapter<CharSequence> monthSpinnerArrayAdapter;
	private ArrayAdapter<CharSequence> daySpinnerArrayAdapter;
	private ArrayAdapter<CharSequence> yearSpinnerArrayAdapter;
	private ArrayAdapter<CharSequence> orderStateSpinnerArrayAdapter;
	private ArrayAdapter<CharSequence> transactionFeeSpinnerArrayAdapter;
	private URL url;
	private URLConnection urlConnection;	
	private String merchantID = "";
	private String merchantKEY = "";
	private int timeZoneCode = 0;
	private String timeZone = "";
	private String timeZoneOffset = "";
	private String authKey;
	private CheckoutCheck myOutcheck;
	private ArrayList<Order> orderList;
	private Order currentOrder;
	private StringBuffer buf;
	private StringBuffer buf2;
	private String tagName;
	private String tempXmlText;
	private ArrayList<String[]> orderReport;
	private ArrayList<ItemSummary> itemSummaries;
	private String nextPageToken = null;
	private int newOrderCount = 0;
	private int processedOrderCount = 0;
	private BigDecimal totalGross = new BigDecimal("0.00");
	private BigDecimal totalNet = new BigDecimal("0.00");
	private int totalUnits = 0;
	private String orderStateText;
	private boolean androidTransactionsFees = true;
	private String toastText = "Done.";

    public void onStart()
    {
       super.onStart();
       FlurryAgent.onStartSession(this, "L5WL2EK5QZC7R6RBJ9SA");
       // your code
    }
    
    public void onStop()
    {
       super.onStop();
       FlurryAgent.onEndSession(this);
       // your code
    }
    
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		myOutcheck = this;
        try {
			readXML();
		} catch (XmlPullParserException e) {
		} catch (IOException e) {
		}
		setFullscreen();
		launchMainScreen();		
	}

    public void setFullscreen() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
	
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem information = menu.add(0, INFORMATION_DIALOG, 0, "Information");        
        information.setIcon(R.drawable.info_icon);
        MenuItem editMerchantInfo = menu.add(0, EDIT_MERCHANT_INFORMATION, 0, "Edit Merchant Information");
        editMerchantInfo.setIcon(R.drawable.edit_icon);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case INFORMATION_DIALOG:
            final Dialog informationDialog = new Dialog(this);
            informationDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);        
            informationDialog.setContentView(R.layout.information_dialog);
            TextView aboutText = (TextView) informationDialog.findViewById(R.id.abouttext4);
            Linkify.addLinks(aboutText, Linkify.ALL); 
            Button okButton = (Button) informationDialog.findViewById(R.id.okButton1);
            okButton.setOnClickListener(new View.OnClickListener(){
                public void onClick(View view){
                	informationDialog.dismiss();
                }
            });
            informationDialog.show();
        	return true;
	    case EDIT_MERCHANT_INFORMATION:
	    	showMerchantInfoDialog();
	        return true;
        }
        return false;
    }
    
	public void launchMainScreen() {
		setContentView(R.layout.main);
		initComponents();
        if (merchantID.length() < 2) {
			showMerchantInfoDialog();
        }
	}
	
	
	private void initComponents() {
		final Calendar cal = Calendar.getInstance();
        currentYear = cal.get(java.util.Calendar.YEAR);
		currentMonth = cal.get(Calendar.MONTH)+1;
        currentDay = cal.get(Calendar.DAY_OF_MONTH);
        currentHour = cal.get(Calendar.HOUR_OF_DAY);
        currentMinute = cal.get(Calendar.MINUTE);
		btnConnect = (Button) findViewById(R.id.btnConnect);
		btnConnect.setOnClickListener(new OnClickListener() {
		      @Override
		      public void onClick(View v) {
		    	  newOrderCount = 0;
		    	  processedOrderCount = 0;
		    	  int startMonthVal = startMonthSpinner.getSelectedItemPosition()+1;
		    	  int startDayVal = startDaySpinner.getSelectedItemPosition()+1;
		    	  int startYearVal = currentYear - startYearSpinner.getSelectedItemPosition();
		    	  int endMonthVal = endMonthSpinner.getSelectedItemPosition()+1;
		    	  int endDayVal = endDaySpinner.getSelectedItemPosition()+1;
		    	  int endYearVal = currentYear - endYearSpinner.getSelectedItemPosition();
		    	  startMonth = Integer.toString(startMonthVal);
		    	  startDay = Integer.toString(startDayVal);
		    	  startYear = Integer.toString(startYearVal);
		    	  endMonth = Integer.toString(endMonthVal);
		    	  endDay = Integer.toString(endDayVal);
		    	  endYear = Integer.toString(endYearVal);
		    	  if (currentMonth == endMonthVal && currentDay == endDayVal && currentYear == endYearVal) {
		    		  String endHour = "";
		    		  if (currentMinute < 6) {
		    			  currentMinute = currentMinute+60;
		    			  currentHour = currentHour-1;
		    			  if (currentHour < 0) {
		    				  currentHour = 0;
		    			  }
		    		  }
		    		  if (currentHour < 10) {
		    			  endHour = "0" + Integer.toString(currentHour); 
		    		  } else {
		    			  endHour = Integer.toString(currentHour);
		    		  }
		    		  endTime =  endHour + ":" + Integer.toString(currentMinute-6) + ":" + "00";
		    	  } else {
		    		  endTime = "23:59:59";
		    	  }
		    	  orderStateText = orderStateSpinner.getSelectedItem().toString();
		    	  if (transactionFeeSpinner.getSelectedItemPosition() == 1) {
		    		  androidTransactionsFees = false;
		    	  }
		    	  connectToServer();
		      }
		    });
		
		startMonthSpinner = (Spinner) findViewById(R.id.start_month);
		startDaySpinner = (Spinner) findViewById(R.id.start_day);
		startYearSpinner = (Spinner) findViewById(R.id.start_year);
		endMonthSpinner = (Spinner) findViewById(R.id.end_month);
		endDaySpinner = (Spinner) findViewById(R.id.end_day);
		endYearSpinner = (Spinner) findViewById(R.id.end_year);		
		
    	monthSpinnerArrayAdapter = ArrayAdapter.createFromResource(
                this, R.array.months, android.R.layout.simple_spinner_item);
        monthSpinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);	
        daySpinnerArrayAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);        
        daySpinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        for (int i = 1; i < 32; i++) {
        	daySpinnerArrayAdapter.add(Integer.toString(i));	
        }
        yearSpinnerArrayAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);        
        yearSpinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        for (int i = currentYear; i > currentYear-30; i--) {
        	yearSpinnerArrayAdapter.add(Integer.toString(i));	
        } 
        
        startMonthSpinner.setAdapter(monthSpinnerArrayAdapter);
        startDaySpinner.setAdapter(daySpinnerArrayAdapter);
        startYearSpinner.setAdapter(yearSpinnerArrayAdapter);
        endMonthSpinner.setAdapter(monthSpinnerArrayAdapter);
        endDaySpinner.setAdapter(daySpinnerArrayAdapter);
        endYearSpinner.setAdapter(yearSpinnerArrayAdapter);
                   
        startMonthSpinner.setSelection(currentMonth-1);
        startDaySpinner.setSelection(currentDay-1);
        endMonthSpinner.setSelection(currentMonth-1);
        endDaySpinner.setSelection(currentDay-1);
        
        orderStateSpinner = (Spinner) findViewById(R.id.order_state);
        transactionFeeSpinner = (Spinner) findViewById(R.id.transaction_fee);	
        orderStateSpinnerArrayAdapter = ArrayAdapter.createFromResource(
                this, R.array.order_states, R.layout.my_spinner_style);
        orderStateSpinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        transactionFeeSpinnerArrayAdapter = ArrayAdapter.createFromResource(
                this, R.array.transaction_fees, R.layout.my_spinner_style);
        transactionFeeSpinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        orderStateSpinner.setAdapter(orderStateSpinnerArrayAdapter);
        transactionFeeSpinner.setAdapter(transactionFeeSpinnerArrayAdapter);
        
	}


    public void connectToServer() {              
        myProgressDialog = ProgressDialog.show(this, "Please wait...", "Retrieving Data", true, false);       
        Thread thread = new Thread(this);
        thread.start();
    }
	
    
	@Override
	public void run() {
		String combinedMerchantInfo = merchantID + ":" + merchantKEY;
		byte[] encoded = Base64.encodeBase64(combinedMerchantInfo.getBytes());
		String encodedString = new String(encoded);
		authKey = "Basic " + encodedString;		
		
		String xmlRequest = 
			"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
			"<notification-history-request xmlns=\"http://checkout.google.com/schema/2\">" +
			"<start-time>" + startYear + "-" + startMonth + "-" + startDay + "T00:00:00" + timeZoneOffset + "</start-time>" +
			"<end-time>" + endYear + "-" + endMonth + "-" + endDay + "T" + endTime + timeZoneOffset + "</end-time>" +
	        "<notification-types>" +
	        "<notification-type>new-order</notification-type>" +
	        "</notification-types>" +
			"</notification-history-request>";
		
		String xmlRequestNextPage = "";
		
		String xmlRequest2 = 
			"<order-list-request xmlns=\"http://checkout.google.com/schema/2\" " +
			"start-date=\"" + startYear + "-" + startMonth + "-" + startDay + "T00:00:00\" " +
			"end-date=\"" + endYear + "-" + endMonth + "-" + endDay + "T" + endTime + "\">" +
			"<date-time-zone>" + timeZone + "</date-time-zone>" +
			"</order-list-request>";
		

		/////////////Request Notification History/////////////////////////////////
		
		try {
			url = new URL("https://checkout.google.com/api/checkout/v2/reports/Merchant/" + merchantID);
			try {
				urlConnection = url.openConnection();
			} catch (IOException e) {
				e.printStackTrace();
			}
			urlConnection.setRequestProperty("Authorization", authKey);
			urlConnection.setRequestProperty("Content-Type", "application/xml;charset=UTF-8");
			urlConnection.setRequestProperty("Accept", "application/xml;charset=UTF-8");
			urlConnection.setDoOutput(true); 
			OutputStreamWriter wr = null;
			try {
				wr = new OutputStreamWriter(urlConnection.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				wr.write(xmlRequest);
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				wr.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}	
			BufferedReader rd = null;
			try {
				rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			} catch (IOException e) {
				e.printStackTrace();
			}
			String line;
			buf = new StringBuffer();
			if (rd != null) {
				try {
					while ((line = rd.readLine()) != null) {
						if (line.contains("item-name") || line.contains("google-order-number") || line.contains("next-page-token")) {
							buf.append(line+"\n");							
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}				
			} else {
				toastText = "Error: No data found.";
			}
			try {
				wr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (rd != null) {
				try {
					rd.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
	    	orderList = new ArrayList<Order>();
			buildOrderList(buf.toString());
			
			
			///////////////If Notification History has more than 50 orders, keep requesting next page////////////
			
			while (nextPageToken != null) {
				xmlRequestNextPage = 
					"<notification-history-request xmlns=\"http://checkout.google.com/schema/2\">" +
				    "<next-page-token>" + nextPageToken + "</next-page-token>" +
				    "</notification-history-request>";
				url = new URL("https://checkout.google.com/api/checkout/v2/reports/Merchant/" + merchantID);
				try {
					urlConnection = url.openConnection();
				} catch (IOException e) {
					e.printStackTrace();
				}
				urlConnection.setRequestProperty("Authorization", authKey);
				urlConnection.setRequestProperty("Content-Type", "application/xml;charset=UTF-8");
				urlConnection.setRequestProperty("Accept", "application/xml;charset=UTF-8");
				urlConnection.setDoOutput(true); 
				wr = null;
				try {
					wr = new OutputStreamWriter(urlConnection.getOutputStream());
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					wr.write(xmlRequestNextPage);
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					wr.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}	
				rd = null;
				try {
					rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
				} catch (IOException e) {
					e.printStackTrace();
				}
				buf = new StringBuffer();
				try {
					while ((line = rd.readLine()) != null) {
						if (line.contains("item-name") || line.contains("google-order-number") || line.contains("next-page-token")) {
							buf.append(line+"\n");							
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					wr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					rd.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				buildOrderList(buf.toString());
			}
			
			
			
			///////////////Request Order Report//////////////////
			
			orderReport = new ArrayList<String[]>();
			url = new URL("https://checkout.google.com/api/checkout/v2/reports/Merchant/" + merchantID);
			try {
				urlConnection = url.openConnection();
			} catch (IOException e) {
				e.printStackTrace();
			}
			urlConnection.setRequestProperty("Authorization", authKey);
			urlConnection.setRequestProperty("Content-Type", "application/xml;charset=UTF-8");
			urlConnection.setRequestProperty("Accept", "application/xml;charset=UTF-8");
			urlConnection.setDoOutput(true); 
						
			OutputStreamWriter wr2 = null;
			try {
				wr2 = new OutputStreamWriter(urlConnection.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				wr2.write(xmlRequest2);
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				wr2.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}	
			try {
				rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (rd != null) {
				try {
					while ((line = rd.readLine()) != null) {
						String[] results = line.split(",");
						orderReport.add(results);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				toastText = "Error: No data found.";
			}
			try {
				wr2.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (rd != null) {
				try {
					rd.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			FileOutputStream fOut = null;
			try {
				fOut = openFileOutput("output.txt", MODE_WORLD_WRITEABLE);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			OutputStreamWriter osw = new OutputStreamWriter(fOut); 
			try {
				osw.write(buf.toString());
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				osw.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				osw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} 
		handler.sendEmptyMessage(0);
	}
 	
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            myProgressDialog.dismiss();			
			produceReport();
            Toast.makeText(myOutcheck, toastText, Toast.LENGTH_SHORT).show();
        }
    };
	
    
    
    private void buildOrderList(String newXmlResponse) {
    	nextPageToken = null;
    	XmlPullParserFactory factory = null;
		try {
			factory = XmlPullParserFactory.newInstance();
		} catch (XmlPullParserException e) {
		}
        factory.setNamespaceAware(true);
	    XmlPullParser xpp = null;
		try {
			xpp = factory.newPullParser();
		} catch (XmlPullParserException e) {
		}
        try {
			xpp.setInput(new StringReader(newXmlResponse));
		} catch (XmlPullParserException e) {
		}           
    	int eventType = 0;
		try {
			eventType = xpp.getEventType();
		} catch (XmlPullParserException e) {
		}
        while (eventType != XmlPullParser.END_DOCUMENT) {
	          if(eventType == XmlPullParser.START_DOCUMENT) {
	          } else if(eventType == XmlPullParser.END_DOCUMENT) {
	          } else if(eventType == XmlPullParser.START_TAG) {
	              tagName = xpp.getName();              
	          } else if(eventType == XmlPullParser.END_TAG) {
	          } else if(eventType == XmlPullParser.TEXT) { 
	              if (tagName.equals("google-order-number")) {
	            	  tempXmlText = xpp.getText().toString();
	            	  if (!tempXmlText.contains("\n")) {
			              currentOrder = new Order(tempXmlText);
			              newOrderCount++;
	            	  }	            		  
	              }
	              if (tagName.equals("item-name")) {
	            	  tempXmlText = xpp.getText().toString();
	            	  if (!tempXmlText.contains("\n")) {
			              currentOrder.setItemName(tempXmlText);
			              orderList.add(currentOrder);
	            	  }	            		  
	              }
	              if (tagName.equals("next-page-token")) {
	            	  tempXmlText = xpp.getText().toString();
	            	  if (!tempXmlText.contains("\n")) {	
			              nextPageToken = tempXmlText;
	            	  }	            		  
	              }
	          }
	        try {
				eventType = xpp.next();
			} catch (XmlPullParserException e) {
			} catch (IOException e) {
			}
        }   	
    }
    
    private void addChargeInfoToOrderList() {
    	Iterator<Order> it = orderList.iterator(); 
		while(it.hasNext()) {
		    Order tempOrder = it.next(); 
		    String tempGoogleOrderNumber = tempOrder.getGoogleOrderNumber();
	    	Iterator<String[]> it2 = orderReport.iterator(); 
			while(it2.hasNext()) {
			    String[] tempOrderLine = it2.next(); 
			    if (tempGoogleOrderNumber.equals(tempOrderLine[0])) {
			    	processedOrderCount++;
			    	BigDecimal itemPrice = new BigDecimal(tempOrderLine[5]);
			    	tempOrder.setItemPrice(itemPrice);
			    	tempOrder.setFinancialState(tempOrderLine[7]);
			    }
			}		    
		}		
    }
    
    
    private void produceReport() {
		addChargeInfoToOrderList();	
    	if (processedOrderCount > 0) {
    		toastText = "Done.";
	        itemSummaries = new ArrayList<ItemSummary>();			
			Set<String> itemNames = new HashSet<String>();
	    	Iterator<Order> it = orderList.iterator(); 
			while(it.hasNext()) {
			    Order tempOrder = it.next();
			    itemNames.add(tempOrder.getItemName());
			}
	    	Iterator<String> it2 = itemNames.iterator(); 
			while(it2.hasNext()) {
			    String tempName = it2.next();
			    ItemSummary tempItemSummary = new ItemSummary(tempName);
			    tempItemSummary.setAndroidTransactions(androidTransactionsFees);
		    	Iterator<Order> it3 = orderList.iterator(); 
				while(it3.hasNext()) {
				    Order tempOrder = it3.next();
				    if (tempName.equals(tempOrder.getItemName())) {
				    	BigDecimal tempItemPrice = tempOrder.getItemPrice();
				    	if (tempOrder.getFinancialState().equals(orderStateText)) {
					    	tempItemSummary.incrementItemCount();
					    	totalUnits++;
					    	tempItemSummary.setItemPrice(tempItemPrice);
					    	System.out.println(tempItemPrice);
				    	}
				    }
				}
				int numItems = tempItemSummary.getItemCount();
				if (numItems > 0) {
				    itemSummaries.add(tempItemSummary);				
				}
			}	
			NameComparator nc = new NameComparator();
			Collections.sort(itemSummaries,nc);						
			setContentView(R.layout.report);
			final ListView itemSummaryList = (ListView)findViewById(R.id.item_summary_list); 	
			ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
	    	Iterator<ItemSummary> it4 = itemSummaries.iterator(); 
			MathContext mc = new MathContext(BigDecimal.ROUND_HALF_UP);
			totalGross.setScale(2, BigDecimal.ROUND_HALF_UP);
			totalNet.setScale(2, BigDecimal.ROUND_HALF_UP);
			while(it4.hasNext()) {
			    ItemSummary tempItemSummary = it4.next();
			    tempItemSummary.calcTotalGross();
			    tempItemSummary.calcTotalNet();
			    totalGross = totalGross.add(tempItemSummary.getTotalGross(),mc);
			    totalNet = totalNet.add(tempItemSummary.getTotalNet(),mc);
			    DecimalFormat df = new DecimalFormat("0.00");
			    String formattedTotalGross = df.format(tempItemSummary.getTotalGross());
			    String formattedTotalNet = df.format(tempItemSummary.getTotalNet());
			    
			    HashMap<String,String> item = new HashMap<String,String>();
				item.put( "text1",tempItemSummary.getItemName().replaceAll(" ", "") );
				item.put( "text2",Integer.toString(tempItemSummary.getItemCount()) );
				item.put( "text3",formattedTotalGross );
				item.put( "text4",formattedTotalNet );
				list.add( item );
			}
			
			
			SimpleAdapter summaryAdapter = new SimpleAdapter( 
					this, 
					list,
					R.layout.report_item,
					new String[] { "text1","text2","text3","text4" },
					new int[] { R.id.item_label, R.id.units_label, R.id.gross_label, R.id.net_label } );
			
			itemSummaryList.setAdapter(summaryAdapter);
			itemSummaryList.setFocusable(false);
			
			TextView totalUnitsView = (TextView) findViewById(R.id.total_units);
			TextView totalGrossView = (TextView) findViewById(R.id.total_gross);
			TextView totalNetView = (TextView) findViewById(R.id.total_net);		
			totalUnitsView.setText(Integer.toString(totalUnits));
		    DecimalFormat df = new DecimalFormat("0.00");
		    String formattedTotalGrossValue = df.format(totalGross);
		    String formattedTotalNetValue = df.format(totalNet);
		    totalGrossView.setText(formattedTotalGrossValue);
		    totalNetView.setText(formattedTotalNetValue);			
		    TextView reportDateRange = (TextView) findViewById(R.id.report_date);
		    reportDateRange.setText(startYear + "-" + startMonth + "-" + startDay + " to " + 
		    		endYear + "-" + endMonth + "-" + endDay + " (" + orderStateText + ")");		   		    
			backButton = (Button) findViewById(R.id.btnBack);
			backButton.setOnClickListener(new OnClickListener() {
			      @Override
			      public void onClick(View v) {
			    	  totalUnits = 0;
			    	  totalGross = new BigDecimal("0.00");
			    	  totalNet = new BigDecimal("0.00");
			    	  launchMainScreen();
			      }
			    });
    	} else {
    		toastText = "Error: No data found.";
    	}
    }
    

    class NameComparator implements Comparator<ItemSummary> {
    	  public int compare(ItemSummary is1, ItemSummary is2) {    		  
    	      String s1 = is1.getItemName();
    	      String s2 = is2.getItemName();
    	      return s1.compareTo(s2);
    	  }
    	}

    public void readXML() throws XmlPullParserException, IOException {
    	XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
	    XmlPullParser xpp = factory.newPullParser();       
         try {        	 
        	 InputStream in = openFileInput("merchant_info.xml");
        	 InputStreamReader isr = new InputStreamReader(in);
        	 BufferedReader reader = new BufferedReader(isr);
        	 String str;
        	 StringBuffer buf = new StringBuffer();
        	 while ((str = reader.readLine()) != null) {
        		 buf.append(str);
        	 }
        	 in.close(); 
             xpp.setInput(new StringReader(buf.toString()));           
        	 int eventType = xpp.getEventType();
             while (eventType != XmlPullParser.END_DOCUMENT) {
              if(eventType == XmlPullParser.START_DOCUMENT) {
              } else if(eventType == XmlPullParser.END_DOCUMENT) {
              } else if(eventType == XmlPullParser.START_TAG) {
                  tagName = xpp.getName();
              } else if(eventType == XmlPullParser.END_TAG) {
              } else if(eventType == XmlPullParser.TEXT) {  
                  if (tagName.contains("merchant_id")) {
                	  merchantID = xpp.getText().toString();
                  }
                  if (tagName.contains("merchant_key")) {
                	  merchantKEY = xpp.getText().toString();
                  }
                  if (tagName.contains("time_zone")) {
                	  timeZoneCode = Integer.parseInt(xpp.getText().toString());
                  }
              }
              eventType = xpp.next();
             }
             setTimeZoneText();
         } catch (Exception FileNotFoundException){
         } 
    }
    
    public void writeXML() {
		try {
			String fileName = "merchant_info";
			FileOutputStream fOut = openFileOutput(fileName + ".xml", MODE_WORLD_WRITEABLE);
			StringBuffer profileXML = new StringBuffer();
			profileXML.append("<merchant_id>" + merchantID + "</merchant_id>\n");
			profileXML.append("<merchant_key>" + merchantKEY + "</merchant_key>\n");
			profileXML.append("<time_zone>" + timeZoneCode + "</time_zone>\n");			
			OutputStreamWriter osw = new OutputStreamWriter(fOut); 		
			osw.write(profileXML.toString());
			osw.flush();
			osw.close();
		 } catch (IOException ioe) {
	         ioe.printStackTrace();
	    }
    }
	
    private void setTimeZoneText() {
    	if (timeZoneCode == 0) {
    		timeZone = "Pacific/Midway";
    		timeZoneOffset = "-11:00";
    	}
    	if (timeZoneCode == 1) {
    		timeZone = "Etc/GMT+10";
    		timeZoneOffset = "-10:00";
    	}
    	if (timeZoneCode == 2) {
    		timeZone = "America/Anchorage";
    		timeZoneOffset = "-09:00";
    	}
    	if (timeZoneCode == 3) {
    		timeZone = "America/Los_Angeles";
    		timeZoneOffset = "-08:00";
    	}
    	if (timeZoneCode == 4) {
    		timeZone = "America/Denver";
    		timeZoneOffset = "-07:00";
    	}
    	if (timeZoneCode == 5) {
    		timeZone = "America/Chicago";
    		timeZoneOffset = "-06:00";
    	}
    	if (timeZoneCode == 6) {
    		timeZone = "Etc/GMT+5";
    		timeZoneOffset = "-05:00";
    	}
    	if (timeZoneCode == 7) {
    		timeZone = "Etc/GMT+4";
    		timeZoneOffset = "-04:00";
    	}
    	if (timeZoneCode == 8) {
    		timeZone = "Etc/GMT+3";
    		timeZoneOffset = "-03:00";
    	}
    	if (timeZoneCode == 9) {
    		timeZone = "Etc/GMT+2";
    		timeZoneOffset = "-02:00";
    	}
    	if (timeZoneCode == 10) {
    		timeZone = "Etc/GMT+1";
    		timeZoneOffset = "-01:00";
    	}
    	if (timeZoneCode == 11) {
    		timeZone = "Etc/GMT";
    		timeZoneOffset = "-00:00";
    	}
    	if (timeZoneCode == 12) {
    		timeZone = "Etc/GMT-1";
    		timeZoneOffset = "+01:00";
    	}
    	if (timeZoneCode == 13) {
    		timeZone = "Etc/GMT-2";
    		timeZoneOffset = "+02:00";
    	}
    	if (timeZoneCode == 14) {
    		timeZone = "Etc/GMT-3";
    		timeZoneOffset = "+03:00";
    	}
    	if (timeZoneCode == 15) {
    		timeZone = "Etc/GMT-4";
    		timeZoneOffset = "+04:00";
    	}
    	if (timeZoneCode == 16) {
    		timeZone = "Etc/GMT-5";
    		timeZoneOffset = "+05:00";
    	}
    	if (timeZoneCode == 17) {
    		timeZone = "Etc/GMT-6";
    		timeZoneOffset = "+06:00";
    	}
    	if (timeZoneCode == 18) {
    		timeZone = "Etc/GMT-7";
    		timeZoneOffset = "+07:00";
    	}
    	if (timeZoneCode == 19) {
    		timeZone = "Etc/GMT-8";
    		timeZoneOffset = "+08:00";
    	}
    	if (timeZoneCode == 20) {
    		timeZone = "Etc/GMT-9";
    		timeZoneOffset = "+09:00";
    	}
    	if (timeZoneCode == 21) {
    		timeZone = "Etc/GMT-10";
    		timeZoneOffset = "+10:00";
    	}
    	if (timeZoneCode == 22) {
    		timeZone = "Etc/GMT-11";
    		timeZoneOffset = "+11:00";
    	}
    	if (timeZoneCode == 23) {
    		timeZone = "Etc/GMT-12";
    		timeZoneOffset = "+12:00";
    	}
    }
    
    private void showMerchantInfoDialog() {
    	final Dialog merchantInfoDialog = new Dialog(this);
    	merchantInfoDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
    	merchantInfoDialog.setContentView(R.layout.merchant_info_dialog);
        Button submitButton = (Button) merchantInfoDialog.findViewById(R.id.btnSubmit);
        Button cancelButton = (Button) merchantInfoDialog.findViewById(R.id.btnCancel);  
        final EditText merchantIdField = (EditText) merchantInfoDialog.findViewById(R.id.merchant_id); 
        final EditText merchantKeyField = (EditText) merchantInfoDialog.findViewById(R.id.merchant_key); 
    	final Spinner timeZoneSpinner = (Spinner) merchantInfoDialog.findViewById(R.id.time_zone);
    	merchantIdField.setText(merchantID);
    	merchantKeyField.setText(merchantKEY);
    	ArrayAdapter<CharSequence> timeZoneSpinnerArrayAdapter;
    	timeZoneSpinnerArrayAdapter = ArrayAdapter.createFromResource(this, R.array.time_zones, android.R.layout.simple_spinner_item);
    	timeZoneSpinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        timeZoneSpinner.setAdapter(timeZoneSpinnerArrayAdapter);
    	timeZoneSpinner.setSelection(timeZoneCode);   	      
        submitButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view){ 
            	merchantID = merchantIdField.getText().toString();
            	merchantKEY = merchantKeyField.getText().toString();
            	timeZoneCode = timeZoneSpinner.getSelectedItemPosition();
            	setTimeZoneText();
            	writeXML();
            	merchantInfoDialog.dismiss(); 
            }
        }); 
        cancelButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view){             	
            	merchantInfoDialog.dismiss(); 
            }
        }); 
        merchantInfoDialog.show();  
    }
    
    
}